package com.zdsoft.finance.product.repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import com.zdsoft.finance.product.entity.Product;
import com.zdsoft.framework.core.common.domain.BaseEntity;
import com.zdsoft.framework.core.common.util.ObjectHelper;

/**
 * 产品操作仓库自定义实现
 * @author longwei
 * @date 2016/11/22
 * @version 1.0
 */
public class ProductRepositoryImpl {
	//查询头部
	private StringBuffer hqlBuffer = new StringBuffer("from Product where 1=1 ");
	
	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 通过产品对象查询并分页
	 * @param product 查询对象
	 * @param pageable 分页信息
	 * @return 分页结果
	 */
	@SuppressWarnings("unchecked")
	public Page<Product> findByProduct(Product product, Pageable pageable){
		//条件组装
		StringBuffer whereHqlBuffer = new StringBuffer(" and isDeleted=:isDeleted");
		if(ObjectHelper.isNotEmpty(product.getCode())){
			whereHqlBuffer.append(" and code = :code ");
		}
		if(ObjectHelper.isNotEmpty(product.getName())){
			whereHqlBuffer.append(" and name like :name");
		}
		if(ObjectHelper.isNotEmpty(product.getCustomCd())){
			whereHqlBuffer.append(" and customCd = :customCd");
		}
		if(ObjectHelper.isNotEmpty(product.getIsEffect())){
			whereHqlBuffer.append(" and isEffect = :isEffect");
		}
		whereHqlBuffer.append(" order by createTime desc");
		
		//参数组装
		Query query = em.createQuery(this.hqlBuffer.toString() + whereHqlBuffer.toString());
		Query countQ = em.createQuery("select count(*) " + this.hqlBuffer.toString() + whereHqlBuffer.toString());
		query.setParameter("isDeleted",!BaseEntity.DELETED);
		countQ.setParameter("isDeleted", !BaseEntity.DELETED);
		
		if(ObjectHelper.isNotEmpty(product.getCode())){
			query.setParameter("code",product.getCode());
			countQ.setParameter("code",product.getCode());
		}
		if(ObjectHelper.isNotEmpty(product.getName())){
			query.setParameter("name","%"+product.getName()+"%");
			countQ.setParameter("name","%"+product.getName()+"%");
		}
		if(ObjectHelper.isNotEmpty(product.getCustomCd())){
			query.setParameter("customCd",product.getCustomCd());
			countQ.setParameter("customCd",product.getCustomCd());
		}
		if(ObjectHelper.isNotEmpty(product.getIsEffect())){
			query.setParameter("isEffect",product.getIsEffect());
			countQ.setParameter("isEffect",product.getIsEffect());
		}
		
		//查询
		query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
		query.setMaxResults(pageable.getPageSize());
		Page<Product> pager = new PageImpl<>(query.getResultList(),pageable,(Long)countQ.getSingleResult());
		return pager;
	}
}
